<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
</head>
<body>
  <div><h1 id="node-js-fs-">Node.js fs 模块</h1>
<h2 id="labdoc-header-0">一、实验介绍</h2>
<h3 id="labdoc-header-1">1.1 实验内容</h3>
<p>出于安全考虑，浏览器端的JavaScript代码一般无法访问本地文件系统。但对于运行在服务器端的Node.js来说，文件系统是可以直接访问的，Node.js中,<code>fs</code>模块可以对系统文件及目录进行读写操作。<br>本次实验将带你探索fs模块。</p><h3 id="labdoc-header-2">1.2 实验知识点</h3>
<ul>
<li><code>fs</code>模块的常见操作</li>
<li><code>同步</code>和<code>异步</code>的区别及适用场景</li>
</ul>
<h3 id="labdoc-header-3">1.3 实验环境</h3>
<ul>
<li>Xfce终端</li>
<li>Node.js v4.2.1</li>
<li>gedit/vim：文本编辑</li>
</ul>
<h2 id="labdoc-header-4">二、实验步骤</h2>
<h3 id="labdoc-header-5">2.1 同步和异步</h3>
<p>不同于C++、Java等编程语言，JavaScript语句是异步执行的，Node.js也是如此。异步使得Node.js能够"同时"处理多个请求，提高了服务程序的并发性。异步特性也是Node.js得以流行的原因之一。</p><p>fs模块中所有方法都有同步和异步两种形式，我们可以在学习fs模块本身的同时体会异步和同步的差别。</p><p>异步方法中回调函数的第一个参数总是留给异常参数（exception），如果方法成功完成，那么这个参数为<code>null</code>或者<code>undefined</code>。</p><p>异步方法实例代码（无需在虚拟机中编写）：</p><pre><code class="hljs javascript"><span class="hljs-keyword"><span class="hljs-keyword">var</span></span> fs = <span class="hljs-built_in"><span class="hljs-built_in">require</span></span>(<span class="hljs-string"><span class="hljs-string">'fs'</span></span>); <span class="hljs-comment"><span class="hljs-comment">// 载入fs模块</span></span>

fs.unlink(<span class="hljs-string"><span class="hljs-string">'/tmp/bestqd'</span></span>, <span class="hljs-function"><span class="hljs-keyword"><span class="hljs-function"><span class="hljs-keyword">function</span></span></span><span class="hljs-function">(</span><span class="hljs-params"><span class="hljs-function"><span class="hljs-params">err</span></span></span><span class="hljs-function">) </span></span>{
    <span class="hljs-keyword"><span class="hljs-keyword">if</span></span> (err) {
        <span class="hljs-keyword"><span class="hljs-keyword">throw</span></span> err;
    }
    <span class="hljs-built_in"><span class="hljs-built_in">console</span></span>.log(<span class="hljs-string"><span class="hljs-string">'成功删除了 /tmp/bestqd'</span></span>);
});
</code></pre><p>同步方法实例代码（无需在虚拟机中编写）：</p><pre><code class="hljs javascript"><span class="hljs-keyword"><span class="hljs-keyword">var</span></span> fs = <span class="hljs-built_in"><span class="hljs-built_in">require</span></span>(<span class="hljs-string"><span class="hljs-string">'fs'</span></span>);

fs.unlinkSync(<span class="hljs-string"><span class="hljs-string">'/tmp/bestqd'</span></span>); <span class="hljs-comment"><span class="hljs-comment">// 函数名最后的Sync 表示是同步方法</span></span>
<span class="hljs-built_in"><span class="hljs-built_in">console</span></span>.log(<span class="hljs-string"><span class="hljs-string">'成功删除了 /tmp/bestqd'</span></span>);
</code></pre><p>同步方法执行完并返回结果后，才能执行后续的代码。而异步方法采用回调函数接收返回结果，可以立即执行后续的代码。</p><h3 id="labdoc-header-6">2.2readFile读取文件</h3>
<p>使用<code>fs.readFile(filename, [options], callback)</code>方法读取文件。</p><p>readFile接收三个参数，filename是文件名；[options]是可选的参数，为一个对象，用于指定文件编码（encoding）及操作方式（flag）；callback是回调函数。</p><p><img src="http://labfile.oss.aliyuncs.com/courses/44/nodejs3-1.png" alt=""></p><p>在虚拟机家目录（/home/bestqd）下新建一个文件<code>text.txt</code>，文件中的内容如下：</p><pre><code class="hljs nginx"><span class="hljs-built_in"><span class="hljs-attribute">line</span></span> <span class="hljs-literal">one</span>
<span class="hljs-built_in">line</span> <span class="hljs-literal">two</span>
</code></pre><p>使用readFile读取此文件，虚拟机家目录下新建文件<code>readfile.js</code>，输入如下代码并保存：</p><pre><code class="hljs javascript"><span class="hljs-keyword"><span class="hljs-keyword">var</span></span> fs = <span class="hljs-built_in"><span class="hljs-built_in">require</span></span>(<span class="hljs-string"><span class="hljs-string">'fs'</span></span>); <span class="hljs-comment"><span class="hljs-comment">// 引入fs模块</span></span>

fs.readFile(<span class="hljs-string"><span class="hljs-string">'./text.txt'</span></span>, <span class="hljs-function"><span class="hljs-keyword"><span class="hljs-function"><span class="hljs-keyword">function</span></span></span><span class="hljs-function">(</span><span class="hljs-params"><span class="hljs-function"><span class="hljs-params">err, data</span></span></span><span class="hljs-function">) </span></span>{
    <span class="hljs-comment"><span class="hljs-comment">// 读取文件失败/错误</span></span>
    <span class="hljs-keyword"><span class="hljs-keyword">if</span></span> (err) {
        <span class="hljs-keyword"><span class="hljs-keyword">throw</span></span> err;
    }
    <span class="hljs-comment"><span class="hljs-comment">// 读取文件成功</span></span>
    <span class="hljs-built_in"><span class="hljs-built_in">console</span></span>.log(data);
});
</code></pre><p>readFile的回调函数接收两个参数，err是读取文件出错时触发的错误对象，data是从文件读取的数据。</p><p>运行程序：</p><pre><code class="hljs">~/ $ <span class="hljs-keyword">node</span> <span class="hljs-title">readfile</span>.js
</code></pre><p>会看到输出的内容类似于这样：</p><pre><code class="hljs apache"><span class="hljs-section">&lt;Buffer </span><span class="hljs-number"><span class="hljs-section">6</span></span><span class="hljs-section">c </span><span class="hljs-number"><span class="hljs-section">69</span></span><span class="hljs-section"> </span><span class="hljs-number"><span class="hljs-section">6</span></span><span class="hljs-section">e </span><span class="hljs-number"><span class="hljs-section">65</span></span><span class="hljs-section"> </span><span class="hljs-number"><span class="hljs-section">20</span></span><span class="hljs-section"> </span><span class="hljs-number"><span class="hljs-section">6</span></span><span class="hljs-section">f </span><span class="hljs-number"><span class="hljs-section">6</span></span><span class="hljs-section">e </span><span class="hljs-number"><span class="hljs-section">65</span></span><span class="hljs-section"> </span><span class="hljs-number"><span class="hljs-section">0</span></span><span class="hljs-section">a </span><span class="hljs-number"><span class="hljs-section">6</span></span><span class="hljs-section">c </span><span class="hljs-number"><span class="hljs-section">69</span></span><span class="hljs-section"> </span><span class="hljs-number"><span class="hljs-section">6</span></span><span class="hljs-section">e </span><span class="hljs-number"><span class="hljs-section">65</span></span><span class="hljs-section"> </span><span class="hljs-number"><span class="hljs-section">20</span></span><span class="hljs-section"> </span><span class="hljs-number"><span class="hljs-section">74</span></span><span class="hljs-section"> </span><span class="hljs-number"><span class="hljs-section">77</span></span><span class="hljs-section"> </span><span class="hljs-number"><span class="hljs-section">6</span></span><span class="hljs-section">f </span><span class="hljs-number"><span class="hljs-section">0</span></span><span class="hljs-section">a&gt;</span>
</code></pre><p>这是原始二进制数据在缓冲区中的内容。要显示文件内容可以使用<code>toString()</code>或者设置输出编码，<code>readFile.js</code>可以改成这样：</p><pre><code class="hljs javascript"><span class="hljs-keyword"><span class="hljs-keyword">var</span></span> fs = <span class="hljs-built_in"><span class="hljs-built_in">require</span></span>(<span class="hljs-string"><span class="hljs-string">'fs'</span></span>); <span class="hljs-comment"><span class="hljs-comment">// 引入fs模块</span></span>

<span class="hljs-comment"><span class="hljs-comment">// 使用toString()</span></span>
fs.readFile(<span class="hljs-string"><span class="hljs-string">'./text.txt'</span></span>, <span class="hljs-function"><span class="hljs-keyword"><span class="hljs-function"><span class="hljs-keyword">function</span></span></span><span class="hljs-function">(</span><span class="hljs-params"><span class="hljs-function"><span class="hljs-params">err, data</span></span></span><span class="hljs-function">) </span></span>{
    <span class="hljs-comment"><span class="hljs-comment">// 读取文件失败/错误</span></span>
    <span class="hljs-keyword"><span class="hljs-keyword">if</span></span> (err) {
        <span class="hljs-keyword"><span class="hljs-keyword">throw</span></span> err;
    }
    <span class="hljs-comment"><span class="hljs-comment">// 读取文件成功</span></span>
    <span class="hljs-built_in"><span class="hljs-built_in">console</span></span>.log(<span class="hljs-string"><span class="hljs-string">'toString: '</span></span>, data.toString());
});

<span class="hljs-comment"><span class="hljs-comment">// 设置编码格式</span></span>
fs.readFile(<span class="hljs-string"><span class="hljs-string">'./text.txt'</span></span>, <span class="hljs-string"><span class="hljs-string">'utf-8'</span></span>, <span class="hljs-function"><span class="hljs-keyword"><span class="hljs-function"><span class="hljs-keyword">function</span></span></span><span class="hljs-function">(</span><span class="hljs-params"><span class="hljs-function"><span class="hljs-params">err, data</span></span></span><span class="hljs-function">) </span></span>{
    <span class="hljs-comment"><span class="hljs-comment">// 读取文件失败/错误</span></span>
    <span class="hljs-keyword"><span class="hljs-keyword">if</span></span> (err) {
        <span class="hljs-keyword"><span class="hljs-keyword">throw</span></span> err;
    }
    <span class="hljs-comment"><span class="hljs-comment">// 读取文件成功</span></span>
    <span class="hljs-built_in"><span class="hljs-built_in">console</span></span>.log(<span class="hljs-string"><span class="hljs-string">'utf-8: '</span></span>, data);
});
</code></pre><p>这样再运行程序就能正常显示出文件中的内容了。</p><p><code>fs.readFileSync(filename, [options])</code>是readFile的同步方法。</p><h3 id="labdoc-header-7">2.3 writeFile写入文件</h3>
<p>使用<code>fs.writeFile(filename, data, [options], callback)</code>写入内容到文件。</p><p>writeFile接收四个参数，filename是文件名称；data是要写入文件的数据；[options]是一个对象为可选参数，包含编码格式（encoding），模式（mode）以及操作方式（flag）；callback是回调函数。</p><p><img src="http://labfile.oss.aliyuncs.com/courses/44/nodejs3-2.png" alt="writeFile"></p><p>在虚拟机家目录下新建<code>writeFile.js</code>文件，输入如下代码并保存：</p><pre><code class="hljs javascript"><span class="hljs-keyword"><span class="hljs-keyword">var</span></span> fs = <span class="hljs-built_in"><span class="hljs-built_in">require</span></span>(<span class="hljs-string"><span class="hljs-string">'fs'</span></span>); <span class="hljs-comment"><span class="hljs-comment">// 引入fs模块</span></span>

<span class="hljs-comment"><span class="hljs-comment">// 写入文件内容（如果文件不存在会创建一个文件）</span></span>
<span class="hljs-comment"><span class="hljs-comment">// 写入时会先清空文件</span></span>
fs.writeFile(<span class="hljs-string"><span class="hljs-string">'./test2.txt'</span></span>, <span class="hljs-string"><span class="hljs-string">'test test'</span></span>, <span class="hljs-function"><span class="hljs-keyword"><span class="hljs-function"><span class="hljs-keyword">function</span></span></span><span class="hljs-function">(</span><span class="hljs-params"><span class="hljs-function"><span class="hljs-params">err</span></span></span><span class="hljs-function">) </span></span>{
    <span class="hljs-keyword"><span class="hljs-keyword">if</span></span> (err) {
        <span class="hljs-keyword"><span class="hljs-keyword">throw</span></span> err;
    }

    <span class="hljs-built_in"><span class="hljs-built_in">console</span></span>.log(<span class="hljs-string"><span class="hljs-string">'Saved.'</span></span>);

    <span class="hljs-comment"><span class="hljs-comment">// 写入成功后读取测试</span></span>
    fs.readFile(<span class="hljs-string"><span class="hljs-string">'./test2.txt'</span></span>, <span class="hljs-string"><span class="hljs-string">'utf-8'</span></span>, <span class="hljs-function"><span class="hljs-keyword"><span class="hljs-function"><span class="hljs-keyword">function</span></span></span><span class="hljs-function">(</span><span class="hljs-params"><span class="hljs-function"><span class="hljs-params">err, data</span></span></span><span class="hljs-function">) </span></span>{
        <span class="hljs-keyword"><span class="hljs-keyword">if</span></span> (err) {
            <span class="hljs-keyword"><span class="hljs-keyword">throw</span></span> err;
        }
        <span class="hljs-built_in"><span class="hljs-built_in">console</span></span>.log(data);
    });
});
</code></pre><p>运行程序：</p><pre><code class="hljs">~/ $ <span class="hljs-keyword">node</span> <span class="hljs-title">writeFile</span>.js
</code></pre><p>如果要追加数据到文件，可以传递一个<code>flag</code>参数，修改代码为如下所示：</p><pre><code class="hljs javascript"><span class="hljs-keyword"><span class="hljs-keyword">var</span></span> fs = <span class="hljs-built_in"><span class="hljs-built_in">require</span></span>(<span class="hljs-string"><span class="hljs-string">'fs'</span></span>); <span class="hljs-comment"><span class="hljs-comment">// 引入fs模块</span></span>

<span class="hljs-comment"><span class="hljs-comment">// 写入文件内容（如果文件不存在会创建一个文件）</span></span>
<span class="hljs-comment"><span class="hljs-comment">// 传递了追加参数 { 'flag': 'a' } </span></span>
fs.writeFile(<span class="hljs-string"><span class="hljs-string">'./test2.txt'</span></span>, <span class="hljs-string"><span class="hljs-string">'test test'</span></span>, { <span class="hljs-string"><span class="hljs-string">'flag'</span></span>: <span class="hljs-string"><span class="hljs-string">'a'</span></span> }, <span class="hljs-function"><span class="hljs-keyword"><span class="hljs-function"><span class="hljs-keyword">function</span></span></span><span class="hljs-function">(</span><span class="hljs-params"><span class="hljs-function"><span class="hljs-params">err</span></span></span><span class="hljs-function">) </span></span>{
    <span class="hljs-keyword"><span class="hljs-keyword">if</span></span> (err) {
        <span class="hljs-keyword"><span class="hljs-keyword">throw</span></span> err;
    }

    <span class="hljs-built_in"><span class="hljs-built_in">console</span></span>.log(<span class="hljs-string"><span class="hljs-string">'Saved.'</span></span>);

    <span class="hljs-comment"><span class="hljs-comment">// 写入成功后读取测试</span></span>
    fs.readFile(<span class="hljs-string"><span class="hljs-string">'./test2.txt'</span></span>, <span class="hljs-string"><span class="hljs-string">'utf-8'</span></span>, <span class="hljs-function"><span class="hljs-keyword"><span class="hljs-function"><span class="hljs-keyword">function</span></span></span><span class="hljs-function">(</span><span class="hljs-params"><span class="hljs-function"><span class="hljs-params">err, data</span></span></span><span class="hljs-function">) </span></span>{
        <span class="hljs-keyword"><span class="hljs-keyword">if</span></span> (err) {
            <span class="hljs-keyword"><span class="hljs-keyword">throw</span></span> err;
        }
        <span class="hljs-built_in"><span class="hljs-built_in">console</span></span>.log(data);
    });
});
</code></pre><p>运行程序：</p><pre><code class="hljs">~/ $ <span class="hljs-keyword">node</span> <span class="hljs-title">writeFile</span>.js
</code></pre><p><code>flag</code>传递的值，<code>r</code>代表读取(read)文件，，<code>w</code>代表写入(write)文件，<code>a</code>代表追加(append)写入文件，还有其他的值不作详细介绍。</p><h3 id="labdoc-header-8">2.4 使用fs.read和fs.write读写文件</h3>
<p>使用<code>fs.read</code>和<code>fs.write</code>读写文件需要使用<code>fs.open</code>打开文件和<code>fs.close</code>关闭文件。</p><h4 id="2-4-1-fs-read-">2.4.1 fs.read()</h4>
<p>先介绍<code>fs.open(path, flags, [mode], callback)</code>方法，此方法用于打开文件，以便fs.read()读取。path是文件路径，flags是打开文件的方式，[mode]是文件的权限（可选参数，默认值是0666），callback是回调函数。</p><p><code>flags</code>的值：</p><ul>
<li><code>r</code> ：读取文件，文件不存在时报错；</li>
<li><code>r+</code> ：读取并写入文件，文件不存在时报错；</li>
<li><code>rs</code> ：以同步方式读取文件，文件不存在时报错；</li>
<li><code>rs+</code> ：以同步方式读取并写入文件，文件不存在时报错；</li>
<li><code>w</code> ：写入文件，文件不存在则创建，存在则清空；</li>
<li><code>wx</code> ：和<code>w</code>一样，但是文件存在时会报错；</li>
<li><code>w+</code> ：读取并写入文件，文件不存在则创建，存在则清空；</li>
<li><code>wx+</code> ：和<code>w+</code>一样，但是文件存在时会报错；</li>
<li><code>a</code> ：以追加方式写入文件，文件不存在则创建；</li>
<li><code>ax</code> ：和<code>a</code>一样，但是文件存在时会报错；</li>
<li><code>a+</code> ：读取并追加写入文件，文件不存在则创建；</li>
<li><code>ax+</code> ：和<code>a+</code>一样，但是文件存在时会报错。</li>
</ul>
<p><code>fs.close(fd, [callback])</code>用于关闭文件，fd是所打开文件的文件描述符。</p><p><code>fs.read(fd, buffer, offset, length, position, callback)</code>方法接收6个参数。</p><ul>
<li><code>fd</code>是文件描述符，必须接收<code>fs.open()</code>方法中的回调函数返回的第二个参数；</li>
<li><code>buffer</code>是存放读取到的数据的Buffer对象；</li>
<li><code>offset</code>指定向buffer中存放数据的起始位置；</li>
<li><code>length</code>指定读取文件中数据的字节数；</li>
<li><code>position</code>指定在文件中读取文件内容的起始位置；</li>
<li><code>callback</code>是回调函数，回调函数的参数：<ul>
<li><code>err</code>用于抛出异常；</li>
<li><code>bytesRead</code>是从文件中读取内容的实际字节数；</li>
<li><code>buffer</code>是被读取的缓存区对象。</li>
</ul>
</li>
</ul>
<p>在家目录中新建文件<code>testread.txt</code>在文件中随意输入一些内容，然后新建<code>read.js</code>文件，输入如下代码并保存：</p><pre><code class="hljs javascript"><span class="hljs-keyword"><span class="hljs-keyword">var</span></span> fs = <span class="hljs-built_in"><span class="hljs-built_in">require</span></span>(<span class="hljs-string"><span class="hljs-string">'fs'</span></span>); <span class="hljs-comment"><span class="hljs-comment">// 引入fs模块</span></span>

<span class="hljs-comment"><span class="hljs-comment">// 打开文件</span></span>
fs.open(<span class="hljs-string"><span class="hljs-string">'./testread.txt'</span></span>, <span class="hljs-string"><span class="hljs-string">'r'</span></span>, <span class="hljs-function"><span class="hljs-keyword"><span class="hljs-function"><span class="hljs-keyword">function</span></span></span><span class="hljs-function">(</span><span class="hljs-params"><span class="hljs-function"><span class="hljs-params">err, fd</span></span></span><span class="hljs-function">) </span></span>{
    <span class="hljs-keyword"><span class="hljs-keyword">if</span></span> (err) {
        <span class="hljs-keyword"><span class="hljs-keyword">throw</span></span> err;
    }
    <span class="hljs-built_in"><span class="hljs-built_in">console</span></span>.log(<span class="hljs-string"><span class="hljs-string">'open file success.'</span></span>);
    <span class="hljs-keyword"><span class="hljs-keyword">var</span></span> buffer = <span class="hljs-keyword"><span class="hljs-keyword">new</span></span> Buffer(<span class="hljs-number"><span class="hljs-number">255</span></span>);
    <span class="hljs-comment"><span class="hljs-comment">// 读取文件</span></span>
    fs.read(fd, buffer, <span class="hljs-number"><span class="hljs-number">0</span></span>, <span class="hljs-number"><span class="hljs-number">10</span></span>, <span class="hljs-number"><span class="hljs-number">0</span></span>, <span class="hljs-function"><span class="hljs-keyword"><span class="hljs-function"><span class="hljs-keyword">function</span></span></span><span class="hljs-function">(</span><span class="hljs-params"><span class="hljs-function"><span class="hljs-params">err, bytesRead, buffer</span></span></span><span class="hljs-function">) </span></span>{
        <span class="hljs-keyword"><span class="hljs-keyword">if</span></span> (err) {
            <span class="hljs-keyword"><span class="hljs-keyword">throw</span></span> err;
        }
        <span class="hljs-comment"><span class="hljs-comment">// 打印出buffer中存入的数据</span></span>
        <span class="hljs-built_in"><span class="hljs-built_in">console</span></span>.log(bytesRead, buffer.slice(<span class="hljs-number"><span class="hljs-number">0</span></span>, bytesRead).toString());

        <span class="hljs-comment"><span class="hljs-comment">// 关闭文件</span></span>
        fs.close(fd);
    });
});
</code></pre><p>运行程序：</p><pre><code class="hljs">~/ $ <span class="hljs-keyword">node</span> <span class="hljs-title">read</span>.js
</code></pre><h4 id="2-4-2-fs-write-">2.4.2 fs.write()</h4>
<p><code>fs.write(fd, buffer, offset, length, position, callback)</code>方法的参数和fs.read()相同，buffer是需要写入文件的内容。</p><p>在家目录中新建文件<code>testwrite.txt</code>，然后新建<code>write.js</code>文件，输入如下代码并保存：</p><pre><code class="hljs js javascript"><span class="hljs-keyword"><span class="hljs-keyword">var</span></span> fs = <span class="hljs-built_in"><span class="hljs-built_in">require</span></span>(<span class="hljs-string"><span class="hljs-string">'fs'</span></span>); <span class="hljs-comment"><span class="hljs-comment">// 引入fs模块</span></span>

<span class="hljs-comment"><span class="hljs-comment">// 打开文件</span></span>
fs.open(<span class="hljs-string"><span class="hljs-string">'./testwrite.txt'</span></span>, <span class="hljs-string"><span class="hljs-string">`w`</span></span>, <span class="hljs-function"><span class="hljs-keyword"><span class="hljs-function"><span class="hljs-keyword">function</span></span></span><span class="hljs-function">(</span><span class="hljs-params"><span class="hljs-function"><span class="hljs-params">err, fd</span></span></span><span class="hljs-function">) </span></span>{
    <span class="hljs-keyword"><span class="hljs-keyword">if</span></span> (err) {
        <span class="hljs-keyword"><span class="hljs-keyword">throw</span></span> err;
    }
    <span class="hljs-built_in"><span class="hljs-built_in">console</span></span>.log(<span class="hljs-string"><span class="hljs-string">'open file success.'</span></span>);
    <span class="hljs-keyword"><span class="hljs-keyword">var</span></span> buffer = <span class="hljs-keyword"><span class="hljs-keyword">new</span></span> Buffer(<span class="hljs-string"><span class="hljs-string">'bestqd'</span></span>);
    <span class="hljs-comment"><span class="hljs-comment">// 读取文件</span></span>
    fs.write(fd, buffer, <span class="hljs-number"><span class="hljs-number">0</span></span>, <span class="hljs-number"><span class="hljs-number">6</span></span>, <span class="hljs-number"><span class="hljs-number">0</span></span>, <span class="hljs-function"><span class="hljs-keyword"><span class="hljs-function"><span class="hljs-keyword">function</span></span></span><span class="hljs-function">(</span><span class="hljs-params"><span class="hljs-function"><span class="hljs-params">err, written, buffer</span></span></span><span class="hljs-function">) </span></span>{
        <span class="hljs-keyword"><span class="hljs-keyword">if</span></span> (err) {
            <span class="hljs-keyword"><span class="hljs-keyword">throw</span></span> err;
        }

        <span class="hljs-built_in"><span class="hljs-built_in">console</span></span>.log(<span class="hljs-string"><span class="hljs-string">'write success.'</span></span>);

        <span class="hljs-comment"><span class="hljs-comment">// 打印出buffer中存入的数据</span></span>
        <span class="hljs-keyword"><span class="hljs-keyword">var</span></span> byteLength = buffer.byteLength;
        <span class="hljs-built_in"><span class="hljs-built_in">console</span></span>.log(byteLength, buffer.slice(<span class="hljs-number"><span class="hljs-number">0</span></span>, byteLength).toString());

        <span class="hljs-comment"><span class="hljs-comment">// 关闭文件</span></span>
        fs.close(fd);
    });
});
</code></pre><p>运行程序：</p><pre><code class="hljs">~/ $ <span class="hljs-keyword">node</span> <span class="hljs-title">write</span>.js
</code></pre><h3 id="labdoc-header-9">2.5 目录操作</h3>
<h4 id="2-5-1-">2.5.1 创建目录</h4>
<p>使用<code>fs.mkdir(path, [mode], callback)</code>创建目录，path是需要创建的目录，[mode]是目录的权限（默认值是0777），callback 是回调函数。</p><p>在家目录下创建<code>mkdir.js</code>文件，输入如下代码并保存：</p><pre><code class="hljs javascript"><span class="hljs-keyword"><span class="hljs-keyword">var</span></span> fs = <span class="hljs-built_in"><span class="hljs-built_in">require</span></span>(<span class="hljs-string"><span class="hljs-string">'fs'</span></span>); <span class="hljs-comment"><span class="hljs-comment">// 引入fs模块</span></span>

<span class="hljs-comment"><span class="hljs-comment">// 创建 newdir 目录</span></span>
fs.mkdir(<span class="hljs-string"><span class="hljs-string">'./newdir'</span></span>, <span class="hljs-function"><span class="hljs-keyword"><span class="hljs-function"><span class="hljs-keyword">function</span></span></span><span class="hljs-function">(</span><span class="hljs-params"><span class="hljs-function"><span class="hljs-params">err</span></span></span><span class="hljs-function">) </span></span>{
    <span class="hljs-keyword"><span class="hljs-keyword">if</span></span> (err) {
        <span class="hljs-keyword"><span class="hljs-keyword">throw</span></span> err;
    }
    <span class="hljs-built_in"><span class="hljs-built_in">console</span></span>.log(<span class="hljs-string"><span class="hljs-string">'make dir success.'</span></span>);
});
</code></pre><p>运行代码：</p><pre><code class="hljs">~/ $ <span class="hljs-keyword">node</span> <span class="hljs-title">mkdir</span>.js
</code></pre><p>运行程序后会发现在当前目录下已经创建了newdir目录，删除目录可以使用<code>fs.rmdir(path, callback)</code>，但是只能删除空目录。</p><h4 id="2-5-2-">2.5.2 读取目录</h4>
<p>使用<code>fs.readdir(path, callback)</code>读取文件目录。</p><p>在家目录下新建<code>readdir.js</code>文件，输入如下代码并保存：</p><pre><code class="hljs javascript"><span class="hljs-keyword"><span class="hljs-keyword">var</span></span> fs = <span class="hljs-built_in"><span class="hljs-built_in">require</span></span>(<span class="hljs-string"><span class="hljs-string">'fs'</span></span>); <span class="hljs-comment"><span class="hljs-comment">// 引入fs模块</span></span>

fs.readdir(<span class="hljs-string"><span class="hljs-string">'./newdir'</span></span>, <span class="hljs-function"><span class="hljs-keyword"><span class="hljs-function"><span class="hljs-keyword">function</span></span></span><span class="hljs-function">(</span><span class="hljs-params"><span class="hljs-function"><span class="hljs-params">err, files</span></span></span><span class="hljs-function">) </span></span>{
    <span class="hljs-keyword"><span class="hljs-keyword">if</span></span> (err) {
        <span class="hljs-keyword"><span class="hljs-keyword">throw</span></span> err;
    }
    <span class="hljs-comment"><span class="hljs-comment">// files是一个数组</span></span>
    <span class="hljs-comment"><span class="hljs-comment">// 每个元素是此目录下的文件或文件夹的名称</span></span>
    <span class="hljs-built_in"><span class="hljs-built_in">console</span></span>.log(files);
});
</code></pre><p>运行代码：</p><pre><code class="hljs">~/ $ <span class="hljs-keyword">node</span> <span class="hljs-title">readdir</span>.js
</code></pre><h3 id="labdoc-header-10">2.6 结束</h3>
<p><code>fs</code>模块中还有很多其他方法，其使用与前面介绍的方法类似，在此不一一介绍，可自行查阅官方API文档。</p><h2 id="labdoc-header-11">三、实验总结</h2>
<ol>
<li>和浏览器端JavaScript不同，Node.js可以访问本地文件系统。</li>
<li><code>fs</code>模块用于文件访问，有同步(函数名最后有sync)和异步(函数名后无sync)两种方式。</li>
<li><code>fs</code>模块提供了丰富的api,没必要提前将它们记住，在需要使用时查阅文档即可。</li>
</ol>
<h2 id="labdoc-header-12">四、参考链接</h2>
<ul>
<li><a href="https://nodejs.xiangfa.org/" target="_blank">https://nodejs.xiangfa.org/</a></li>
</ul>
</div>
</body>
</html>